const express = require('express');
const mongoose = require('mongoose');

const UserModel = require('../models/mongooseSchema').user(mongoose);
const ArticleModel = require('../models/mongooseSchema').article(mongoose);
const MessageModel = require('../models/mongooseSchema').message(mongoose);

const router = express.Router();

function callback(req, res) {
  /** 分页查询
   * 
   * articleSchema.statics = {
   *   paging: (id, populate,cb) => {
   *     if (id) {
   *       return this
   *           .find({ _id: { $lt: id } })
   *           .populate(populate)
   *           .limit(10)
   *           .sort({ _id: -1 })
   *     }
   *     return this
   *           .find()
   *           .populate(populate)
   *           .limit(10)
   *           .sort({ _id: -1 })
   *   },
   * };
   * 
   */
  ArticleModel.count({}, (err, count) => {
    if (err) { console.error('home.js:ArticleModel.count:error'); return res.redirect('back'); }
    ArticleModel // module.paging(find, populate, pagenumber, skip, limit)
      .paging({}, { path: 'author', select: 'name icon profile' }, req.params.pagenumber - 1, 10, 10)
      .then(
        (recdata) => {
          try {
            if (!recdata) throw new Error('至今为止还没有任何文章被发表');
          } catch (e) {
            req.flash('error', e.message);
            return res.redirect('/index=1');
          }
          if (recdata) {
          // 在已经确定有文章被发表的情况下，根据每篇文章的作者索取该作者的头像icon，然后添加到所返回的articles中，为文章缩略页的每篇文章提供头像
            const renderdata = [];
            let i = 0;
            recdata.forEach((data) => {
              renderdata[i] = {
                name: data.author.name,
                icon: data.author.icon,
                profile: data.author.profile,
                _id: data._id,
                title: data.title,
                summary: data.summary,
                content: data.content,
              };
              i += 1;
            });
            res.render('article_index', { res: renderdata, page: count / 10 });
          }
        },
      );
  });
}
// // 首页0
router.get('/', callback);
// 首页1
router.get('/index?=?:pagenumber?', callback);

module.exports = router;
